<?php
ini_set("memory_limit","128M");
ini_set("display_errors", 1); 
include ("../../database.php");

if (!empty($_FILES)) {
	
	$upload_dir = '../../uploads/photos/'; 
	$thumbs_dir = '../../uploads/thumbs/' ;
	$tmp_dir = '../../uploads/tmp/' ;
	$limit = 2048 ;
	$thumb_limit = 200 ;
	$isJpg = false;
	
	$original_filename = $_FILES['Filedata']['name'] ;
	$new_filename = create_file_name($upload_dir);
	$source = $_FILES['Filedata']['tmp_name'] ;
	$tmp_file = $tmp_dir . $original_filename ;
	
	$imageinfo = getimagesize($_FILES['Filedata']['tmp_name']);
	
	
	if($imageinfo['mime'] == 'image/jpg' || $imageinfo['mime'] == 'image/jpeg' ){
		$isJpg=True;
	}
		
	elseif ($imageinfo['mime'] == 'image/png')
		$isJpg=False;
	else{
		echo "error File type not allowed" ;
		exit(1);
	}
	
	
	if (move_uploaded_file($source, $tmp_file));
	{
		$info=insert_into_db($tmp_file, $original_filename, $new_filename, $isJpg);
		
		$save = $upload_dir. $new_filename ; //This is the new file 
		$save_thumb = $thumbs_dir . $new_filename ; //this is the new thumb 
			
		$size=$_FILES['Filedata']['size'];
		
		create_thumb($tmp_file, $save_thumb, $thumb_limit, $isJpg);
		if ( create_image($tmp_file, $save, $limit, $isJpg) == 0 )
			unlink($tmp_file);
		
		$response='';
		foreach ($info as $value)
			$response.=$value.'||||';
		debug_error($response, "w");
		echo $response;
		
	
		
		//return success
		//echo $new_filename;	
	}

	// } else {
	// 	echo 'Invalid file type.';
	// }
}
		
		
function create_image($in,$out,$limit,$isJpg){
	list($width, $height) = getimagesize($in) ; 
	if ( $width > $limit || $height > $limit ){
		
		if ( $width >= $height ){
			$diff = $width / $limit ;
			$new_height = $height / $diff ;
			$new_width = $limit ;
			//debug_error("larghezza", "w");
			
		}
		else { 
			$diff = $height / $limit ;
			$new_width = $width / $diff ;
			$new_height = $limit ;
			//debug_error("altezza", "a");
			
		}
		$tn = imagecreatetruecolor($new_width, $new_height) ; 
		if ($isJpg)
			$image = imagecreatefromjpeg($in) ;
		else $image = imagecreatefrompng($in); 
		imagecopyresampled($tn, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height) ; 
			 
		imagejpeg($tn, $out, 100) ; 
		
		return 0;
	}
	else{
		rename($in,$out);
		return 1;
	}
	
}


//function to create thumb
function create_thumb($in,$out,$thumb_limit,$isJpg){
	list($width, $height) = getimagesize($in) ; 
	if ( $width >= $height ){
			$diff_thumb = $width / $thumb_limit ;
			$thumb_height = $height / $diff_thumb ;
			$thumb_width = $thumb_limit ;
			
		}
		else { 
			$diff_thumb = $height / $thumb_limit ;
			$thumb_width = $width / $diff_thumb ;
			$thumb_height = $thumb_limit ;
			
		}
		$tn = imagecreatetruecolor($thumb_width, $thumb_height) ;
		if ($isJpg) 
			$image = imagecreatefromjpeg($in) ;
		else $image = imagecreatefrompng($in); 
		imagecopyresampled($tn, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height) ; 
			 
		imagejpeg($tn, $out, 100) ; 
}

function insert_into_db($in,$original_filename, $new_filename, $isJpg){
	$userid= $_SESSION['id']=132;
	$array_info=array();
	$ename = $new_filename;
	
	$array_info['original_filename'] = 'original_filename:'.$original_filename;
	$array_info['name']= 'name:'.$ename ;
	
	$query1 = 'INSERT INTO `photos` (photo_name,photo_user_id,photo_filename';
	$query2 = 'VALUES("'.$original_filename.'","'.$userid.'","'.$ename.'"';
	
	if ($isJpg){
		$exif_data = exif_read_data ( $in );
		
		if (isset($exif_data['Make'])){
			$emodel = $exif_data['Make']." ".$exif_data['Model'];
			$array_info['model'] = 'model:'.$emodel;
			$query1 .= ',photo_camera_name';
			$query2 .= ',"'.$emodel.'"';
			
		}
		if (isset($exif_data['ExposureTime'])){
			$eexposuretime = $exif_data['ExposureTime'];
			$array_info['exposure'] = 'exposure:'.$eexposuretime;
			$query1 .= ",photo_exposure_time";
			$query2 .= ',"'.$eexposuretime.'"';
			
		}
			
		if (isset($exif_data['FNumber'])){
			$efnumber = $exif_data['FNumber'];
			$array_info['fnumber'] = 'fnumber:'.$efnumber;
			$query1 .= ",photo_fnumber";
			$query2 .= ',"'.$efnumber.'"';
			
		}
			
		if (isset($exif_data['DateTimeOriginal'])){
			$edate = $exif_data['DateTimeOriginal'];
			$array_info['date'] = 'date:'.$edate;
			$query1 .= ",photo_date";
			$query2 .= ',"'.$edate.'"';
		}
		if (isset($exif_data['LensMake'])){
			$elens= $exif_data['LensMake'];
			$array_info['lensmake'] = 'lensmake:'.$elens;
			$query1 .= ",photo_lens";
			$query2 .= ',"'.$elens.'"';
		}
		if (isset($exif_data['ISO'])){
			$eiso = $exif_data['ISO'];
			$array_info ['ISO']= 'ISO'.$eiso;
			$query1 .= ",photo_ISO";
			$query2 .= ',"'.$eiso.'"';
		}
		if (isset($exif_data['Flash'])){
			$eflash = $exif_data['Flash'];
			$array_info['flash'] = 'flash:'.$eflash;
			$query1 .= ",photo_flash";
			$query2 .= ',"'.$eflash.'"';
		}
		
		if (isset($exif_data['GPSLatitude']) && isset($exif_data['GPSLongitude'])){
			$egps = get_GPS($exif_data)  ;
			$elatitude = $egps[0];
			$elongitude = $egps[1];
			$array_info['coordinates'] = 'coordinates:'.$elatitude.",".$elongitude;
			$query1 .= ",photo_place";
			$query2 .= ',"'.$elatitude.",".$elongitude.'"';
		}
	
	}	
		$query1 .= ") ";
		$query2 .= ") ";
		//debug_error($query1.$query2, "w");
		mysql_query($query1.$query2) or die("Problem inserting photo info in db");
		
		$result=mysql_query("SELECT LAST_INSERT_ID() FROM `photos`");
		$array_info['photo_id'] = 'id:'.mysql_result($result,1);
		
		return $array_info;
	
      
	 
	/*        
	debug_error('Name:'.$ename.'|||||| Make: '.$emake.' |||||| Model: '.$emodel.' ||||||  Exposure time: '.$eexposuretime.
				' ||||||  Fnumber: '.$efnumber.' ||||||  Iso: '.$eiso.' |||||| Date: '.$edate.
				' |||||| Lensmake: '.$elens.' |||||| Flash: '.$eflash.' |||||| GPSLat: '.$elatitude.' |||||| GPSLong: '.$elongitude ,"a");
	*/	
	
	
}

function create_file_name($upload_dir){
	$userid = 'prova-' ;//$_SESSION['id']."-";
	$chars = "1234567890abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_";
	while (true) {
		$i = 0;
		$rand = "";
		while ($i <= 20) {
			$rand .= $chars{mt_rand(0,strlen($chars)-1)};
			$i++;
		}
		if (!file_exists($upload_dir.$rand.".jpg"))
			return $userid.$rand.".jpg";
	}
}
	

function replace_extension($filename) {
	return preg_replace('/\..+$/', '.' . 'jpg', $filename);
}

function debug_error($string,$mode)
{
	$myFile = "../../uploads/tmp/errors.txt";
	if ( $mode == "a" || $mode==null)
		$fh = fopen($myFile, 'a') or die("can't open file");
	else 
		$fh = fopen($myFile, 'w') or die("can't open file");
	$stringData = "-----------------------\n";
	$stringData .= $string;
	$stringData .= "\n-----------------------\n";
	
	fwrite($fh, $stringData);
	
	fclose($fh);
}

function get_GPS($exif){

	if ($exif){
		$lat = $exif['GPSLatitude']; 
		$log = $exif['GPSLongitude'];

		if (!$lat || !$log) return null;
			// latitude values //
		$lat_degrees = divide($lat[0]);
		$lat_minutes = divide($lat[1]);
		$lat_seconds = divide($lat[2]);
		$lat_hemi = $exif['GPSLatitudeRef'];
	
		//longitude values //
		$log_degrees = divide($log[0]);
		$log_minutes = divide($log[1]);
		$log_seconds = divide($log[2]);
		$log_hemi = $exif['GPSLongitudeRef'];
		$lat_decimal = toDecimal($lat_degrees, $lat_minutes, $lat_seconds, $lat_hemi);
		$log_decimal = toDecimal($log_degrees, $log_minutes, $log_seconds, $log_hemi);
	
		return array($lat_decimal, $log_decimal);
	}else return null;
}
 
  function toDecimal($deg, $min, $sec, $hemi)
  {
    $d = $deg + $min/60 + $sec/3600;
    return ($hemi=='S' || $hemi=='W') ? $d*=-1 : $d;
  }
 
  function divide($a)
  {
  // evaluate the string fraction and return a float //	
    $e = explode('/', $a);
  // prevent division by zero //
    if (!$e[0] || !$e[1]) {
      return 0;
    }	else{
    return $e[0] / $e[1];
    }
  }





?>
